package top.hmtools.configuration;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import top.hmtools.base.StringTools;

/**
 * 全局配置
 * @author HyboJ
 *
 */
@Configuration("GMConfiguration")
public class GMConfiguration {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private static String defaultConfigFilePath="config.properties";
	
	private Properties properties;
	
	/**
	 * 本软件版本号
	 */
	private String version;
	
	/**
	 * 是否使用驼峰方式的变量名称
	 */
	private boolean useCamelName = false;

	/**
	 * 初始化
	 */
	@PostConstruct
	public void init(){
		loadProperties(null);
	}
	
	/**
	 * 读取指定的properties配置文件内容，并转换成本配置对象实例
	 * @param path
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void loadProperties(String path){
		properties = new Properties();
		
		InputStream inStream = null;
		
		//读取缺省的配置文件
		if(StringTools.isBlank(path)){
			path = defaultConfigFilePath;
			inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
		}else{
			try {
				inStream = new FileInputStream(path);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				logger.error("读取配置文件\""+path+"\"失败："+e.getMessage(),e);
			}
		}
		try {
			properties.load(inStream);
			Map map = new HashMap();
			map.putAll(properties);
			try {
				BeanUtils.populate(this,map);
				logger.info("配置参数有："+map.toString());
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
				logger.error("转换配置信息失败"+e.getMessage(),e);
			}
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("读取配置文件失败"+e.getMessage(),e);
		}
	}
	
	//######	getter,setter
	
	/**
	 * 获取版本
	 * @return
	 */
	public String getVersion() {
		return version;
	}
	
	/**
	 * 设置版本
	 * @param version
	 */
	public void setVersion(String version) {
		this.version = version;
	}

	/**
	 * 获取缺省的配置文件路径
	 * @return
	 */
	public static String getDefaultConfigFilePath() {
		return defaultConfigFilePath;
	}

	/**
	 * 获取已加载的所有properties配置文件内容集合
	 * @return
	 */
	public Properties getProperties() {
		return properties;
	}

	/**
	 * 是否使用驼峰方式的变量名称
	 * @return the useCamelName
	 */
	public boolean isUseCamelName() {
		return useCamelName;
	}

	/**
	 * 是否使用驼峰方式的变量名称
	 * @param useCamelName the useCamelName to set
	 */
	public void setUseCamelName(boolean useCamelName) {
		this.useCamelName = useCamelName;
	}
	
	
	
	
	
}
